
let token = sessionStorage.getItem("token");
//确定模态框
$("#my-alert").on('close.modal.amui', function () {
    window.location.reload();
});


//封装查询委员方法
function getHotandUsers(searchValue, parents, classname, target) {
    let str2 = "";
    let str4 = "<option value=\"\">-请选择-</option>";
    $.each(searchValue, function (index, value) {
        str2 += " <div class=\"am-panel am-panel-default\">\n" +
            "                                <div   class=\"am-panel-hd\">\n" +
            "                                    <h4 class=\"am-panel-title\" data-am-collapse=\"{parent: '#" + parents + "', target: '#" + value.id + "" + target + "'}\">\n" +
            "                                        " + value.name + "\n" +
            "                                    </h4>\n" +
            "                                </div>\n" +
            "                                <div id=\"" + value.id + "" + target + "\" class=\"am-panel-collapse am-collapse " + classname + "\">\n" +
            "                                    <div class=\"am-panel-bd " + classname + "\">\n";
        if (value.list === null) {
        } else {
            $.each(value.list, function (index, values) {
                str2 += " <div class=\"item\"><input onchange=\"getItem(this)\" name=\"users\" realId=\"" + values.id + "\" value=\"" + values.name + "\" type=\"checkbox\" id=\"" + values.id + "" + target + "\"><label for=\"" + values.id + "" + target + "\">" + values.name + "</label></div>\n"
            });
        }
        str2 += "                                    </div>\n" +
            "                                </div>\n" +
            "                            </div>";
        str4 += "<option value=\"" + value.id + "\">" + value.name + "</option>"
    });
    let objcet = {};
    objcet.str1 = str2;
    objcet.str3 = str4;
    return objcet;
}

$(function () {


//获取常委
let cwlist = "";
    $.ajax({
        async:false,
        url: testurl + "users/list",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({
            "post_id": "1"//职位  委员信息列表传1,2,3  常委传1
        }),
        success:function(data){
            $.each(data.obj,function(index,value){
                cwlist += "<option value=\""+value.id+"\">"+value.realname+"</option>"
            });
            $("#cwlist").html(cwlist);
        }
    })

    // 获取届别
    $.ajax({
        async: false,
        url: testurl + "due/list_nopage",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({}),
        success: function (data) {
            let due = data.obj;
            let str = "";
            $.each(due, function (index, value) {
                if (value.current_flag === "1") {
                    str += "  <option selected value=\"" + value.id + "\">" + value.name + "</option>";
                } else {
                    str += " <option  value=\"" + value.id + "\">" + value.name + "</option>";
                }
            });
            $("#due").html(str);
        }
    });
    // 届别ID
    let due_id = $("#due").val();
    $("#due").on("change", function () {
        due_id = $("#due").val();
        loadData(1);
    });
    //获取身份
    $.ajax({
        async: false,
        url: testurl + "post/list",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({
            "pageNum": "1"
        }),
        success: function (data) {
            let post = data.obj;
            let str4 = " <option value=\"\"></option>";
            $.each(post, function (index, value) {
                str4 += "  <option value=\"" + value.id + "\">" + value.name + "</option>";
            });
            $("#post_id").html(str4);
        }
    });

    // 获取委员小组
    $.ajax({
        async: false,
        url: testurl + "deputy/team/list_nopage",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({
            "type": "2"
        }),
        success: function (data) {
            let group = data.obj;
            let str2 = " <option value=\" \">请选择</option>";
            $.each(group, function (index, value) {
                str2 += "  <option value=\"" + value.id + "\">" + value.name + "</option>";
            });
            $("#group").html(str2);
            $("#deputy_group").html(str2);
        }
    });
    // 委员小组ID
    let deputy_group = "";
    $("#group").on("change", function () {
        deputy_group = $("#group").val();
        loadData(1);
    });
    $("#deputy_group").on("change", function () {
        deputy_group = $("#deputy_group").val();

    });
    // 获取委员团组
    $.ajax({
        async: false,
        url: testurl + "deputy/team/list_nopage",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({
            "type": "1"
        }),
        success: function (data) {
            let organize = data.obj;
            let str3 = " <option value=\" \">请选择</option>";
            $.each(organize, function (index, value) {
                str3 += "  <option value=\"" + value.id + "\">" + value.name + "</option>";
            });
            $("#organize").html(str3);
            $("#deputy_team").html(str3);
        }
    });
    // 委员团组ID
    let deputy_team = "";
    $("#organize").on("change", function () {
        deputy_team = $("#organize").val();
        loadData(1);
    });
    $("#deputy_team").on("change", function () {
        deputy_team = $("#deputy_team").val();

    });

    // 更新委员

    $("#update").click(function () {
        let id = $("#getUserId").val();

        //上传头像
        let head_pic = "";
        // if ($("#changePic").val() === "2"){
        var formdata = new FormData();
        var pic = document.getElementById("head_pic").files;
        for (var j = 0; j < pic.length; j++) {
            formdata.append("" + j + "", pic[j]);
        }
        $.ajax({
            async: false,
            url: testurl + "users/headpic",
            type: "post",
            data: formdata,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                head_pic = data.obj;
            }
        });

        let realname = $("#realname").val();
        let sex = $("input[name='sex']:checked").val();

        let nation = $("#minzu option:selected").val();
        let party_group = $("#dangpai option:selected").val();
        let native_place = $("#native_place").val();
        let positional = $("#zhicheng option:selected").val();
        let health = $("#health option:selected").val();

        let birth = $("#birth").val();
        if (birth === "") {
            birth = null;
        }
        let work_date = $("#birth").val();
        if (work_date === "") {
            work_date = null;
        }
        let major = $("#major").val();
        let education = $("#edu option:selected").val();
        let degree = $("#xuewei option:selected").val();
        let deputy_no = $("#deputy_no").val();
        let college = $("#college").val();
        let nomination_way = $("input[name='nomination_way']:checked").val();
        let deputy_team = $("#tuan option:selected").val();
        let structure = $("#jieg option:selected").val();
        let address = $("#address").val();
        let zip_code = $("#zip_code").val();
        let tel = $("#tel").val();
        let home_tel = $("#home_tel").val();
        let phone = $("#phone").val();
        let resume = $("#resume").val();
        let remark = $("#remark").val();
        let presasg = $("#presasg").val();

        let username = $("#username").val();
        let title_id = $("#zhiwei option:selected").val();
        let src = $("#touxiang").attr("src");
        let str3 = {
            "id": id, "party_group": party_group, "native_place": native_place, "realname": realname, "sex": sex, "nation": nation, "birth": birth,
            "head_pic": head_pic, "positional": positional, "work_date": work_date, "health": health, "deputy_no": deputy_no,
            "major": major, "college": college, "education": education, "degree": degree, "nomination_way": nomination_way,
            "deputy_team": deputy_team, "structure": structure, "address": address, "zip_code": zip_code, "tel": tel, "home_tel": home_tel,
            "phone": phone, "resume": resume, "remark": remark, "presasg": presasg, "username": username, "title_id": title_id
        };



        if (realname === "" || sex === undefined || birth === "" || nation === "" || party_group === "" || (head_pic === "" && src === "")
            || deputy_no === "" || education === "" || presasg === "" || deputy_team === "" || phone === "" || username === "") {
            alert("请填写带*必填项！");
            return false;
        } else {
            $.ajax({
                async: false,
                headers: { "Authorization": "Bearer " + token },
                url: testurl + "users/update",
                contentType: "application/json",
                type: "post",
                data: JSON.stringify(str3),
                success: function (data) {
                    if (data.success === true) {
                        $(".users").html("修改用户");
                        $(".alert").html(data.message);
                        $('#my-alert').modal({ target: '#my-alert' });
                        $('#users').modal('close');
                        loadData(1);
                    } else {

                        $(".users").html("修改用户");
                        $(".alert").html("修改失败：" + data.message);
                        $('#my-alert').modal({ target: '#my-alert' });
                        $('#users').modal('close');
                        loadData(1);
                    }
                },
                error: function (data) {
                    console.log(data);
                }
            });
        }

    });



    //页数
    let pages = 1;
    let group_id = $("#cwlist option:selected").val();
    $("#cwlist").on("change", function () {
        group_id = $("option:selected", this).val();
        loadData(1);
    });
    function loadData(pageNum) {
        $.ajax({
            async: false,
            url: testurl + "users/list_group",
            type: "post",
            headers: { "Authorization": "Bearer " + token },
            contentType: "application/json",
            data: JSON.stringify({
                "pageNum": pageNum,
                "group_flag": "1",//1分工委员列表 2不是分工委员的列表
                "group_id": group_id//常委用户id
            }),
            success: function (data) {
                let dbmessage = data.obj;
                ssd = Math.ceil(data.pageTotal / data.pageSize);
                pages = ssd;
                str = "";
                $.each(dbmessage, function (index, values) {
                    if (values.deputy_group_name === undefined) {
                        values.deputy_group_name = "";
                    }
                    if (values.deputy_team_name === undefined) {
                        values.deputy_team_name = "";
                    }
                    if (values.post_name === undefined) {
                        values.post_name = "";
                    }
                    if (values.deputy_no === undefined) {
                        values.deputy_no = "";
                    }
                    str += " <tr class=\"gradeX\">\n" +
                        "                            <td><input name='selectAll'  class='checked' value=" + values.id + " type='checkbox'></td>\n" +
                        "                                        <td><a style=\"cursor:pointer;\" target=\"_blank\" href=\"userInfo.html?id=" + values.id + "\">" + values.realname + "</a></td>\n" +
                        "                                        <td>" + values.sex_name + "</td>\n" +
                        "                                        <td>" + values.deputy_no + "</td>\n" +
                        "                            <td>" + values.organ_name + "</td>\n" +
                        "                            <td>" + values.presasg + "</td>\n" +
                        "                            <td>" + values.phone + "</td>\n" +
                        "                            <td>" + values.tel + "</td>\n" +
                        "                            <td>" + values.deputy_team_name + "</td>\n" +
                        "                            <td>" + values.status_name + "</td>\n" +


                        "                                    </tr>";

                });
                $("#show").html(str);
            }
        });
    }

    //分页
    let pageNum = 1;
    $(".first").click(function () {
        pageNum = 1;
        loadData(pageNum);
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });
    $(".last").click(function () {
        pageNum = pages;
        loadData(pageNum);
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });
    $(".up").click(function () {
        if (pageNum === 1) {
            return false;
        } else {
            pageNum--;
            loadData(pageNum);
        }
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });
    $(".down").click(function () {
        if (pageNum === pages) {
            return false;
        } else {
            pageNum++;
            loadData(pageNum);
        }
        $(this).parents("li").addClass("am-active");
        $(this).parents("li").siblings().removeClass("am-active");
    });


    loadData(1);
});


//选中所有的checkbox框
$('#checkAll[name="selectAll"]').click(function () {
    if ($(this).is(':checked')) {
        $('#show input[name="selectAll"]').each(function () {

            $(this).prop("checked", true);
        });
    } else {
        $('input[name="selectAll"]').each(function () {
            $(this).removeAttr("checked", false);
        });
    }
});
//获取不是某届委员人员列表选中所有的checkbox框
$('#checkAll2[name="selectAll2"]').click(function () {
    if ($(this).is(':checked')) {
        $('#show2 input[name="selectAll2"]').each(function () {

            $(this).prop("checked", true);
        });
    } else {
        $('input[name="selectAll2"]').each(function () {
            $(this).removeAttr("checked", false);
        });
    }
});




//获取某届委员人员列表

function getListNot() {

   

    let group_id  = $("#cwlist option:selected").val();
    $.ajax({
        url: testurl + "users/teamsAndUsers",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({
            "post": "",//1分工委员列表 2不是分工委员的列表
            "group_id": group_id
        }),
        success: function (data) {
            let hotwords = data.obj;
            let parents = "hotwordsList";
            let classname = "hotwords";
            let target = "222";
            if (hotwords === null) {
            } else {
                let obj = getHotandUsers(hotwords, parents, classname, target);
                $(".hotwords").html(obj.str1);
                $("#hwfenlei").html(obj.str3);
            }
        }
    });
}
//添加委员到列表
function getItem(obj) {
    let only = $("#only").val();
    if (obj.checked) {
        if (only === "1") {
            $(".users").append("<span value=\"" + obj.id + "\" class=\"span" + obj.id + "\">" + obj.value + "</span>&nbsp;&nbsp;");
            $("input[name='users']:not(:checked)").attr("disabled", "")
        } else {
            $(".users").append("<span value=\"" + obj.id + "\" class=\"span" + obj.id + "\">" + obj.value + "</span>&nbsp;&nbsp;");
        }
    } else {
        $(".span" + obj.id).remove();
        $("input[name='users']").removeAttr("disabled");
    }
}


let user_ids = [];
let user_ids2 = [];
let checkedLength = "";
let checkedLength2 = "";
//删除
function check() {

    $.each($('#show input:checkbox:checked'), function () {
        userId = $(this).val();
        user_ids.push(userId);
    });
    checkedLength = $('#show input:checkbox:checked').length;
}
// 添加
function check2() {
    $.each($("input[name='users']:checked"), function () {
        userId = $(this).attr("realid");
        user_ids2.push(userId);
    });
    checkedLength2 = $("input[name='users']:checked").length;
}

//添加常委
$("#go").click(function () {
    let group_id = $("#cwlist option:selected").val();
    check2();
    let ids = user_ids2.toString();
    if (checkedLength2 <= 0) {
        $('#my-alert').modal({ target: '#my-alert' });
        $(".users").html("添加分工委员");
        $(".alert").html("请选择要添加的分工委员！");
        return false;
    } else {
        $.ajax({
            url: testurl + "users/add_cw_group",
            type: "post",
            headers: { "Authorization": "Bearer " + token },
            contentType: "application/json",
            data: JSON.stringify({
                "group_id": group_id,//常委id
                "ids": ids
            }),
            success: function (data) {
                if (data.success === true) {
                    $('#my-popup').modal('close');
                    $(".users").html("添加分工委员");
                    $(".alert").html(data.message);
                    $('#my-alert').modal({ target: '#my-alert' });
                    checkedLength2 = "";
                } else {
                    $('#my-popup').modal('close');
                    $(".users").html("添加分工委员");
                    $(".alert").html(data.message);
                    $('#my-alert').modal({ target: '#my-alert' });
                    checkedLength2 = "";

                }
            }
        });
    }

    return false
});

//查询热词
function searchReci() {
    let group_id = $("#cwlist option:selected").val();
    let name = $("#hw").val();
    let deputy_team = $("#hwfenlei").val();
    $.ajax({
        url: testurl + "users/teamsAndUsers",
        type: "post",
        headers: { "Authorization": "Bearer " + token },
        contentType: "application/json",
        data: JSON.stringify({
            "group_id": group_id,//常委用户id
            "post": "",//1委员选选民   其他常委选委员
            "deputy_team": deputy_team,//委员团组
            "realname": name//热词
        }),
        success: function (data) {
            console.log(data)
            let searchValue = data.obj;
            let parents = "hotwordsResult";
            let classname = "hotwords";
            let target = "444";
            let obj = getHotandUsers(searchValue, parents, classname, target);
            $("#hotwordsResult").html(obj.str1);
        }
    })
}


// 删除委员
$("#dbdelete").click(function () {
    let group_id  = $("#cwlist option:selected").val();
    check();
    let ids = user_ids.toString();
    if (checkedLength <= 0) {
        $('#my-alert').modal({ target: '#my-alert' });
        $(".users").html("删除分工委员");
        $(".alert").html("请选择要删除的分工委员！");
        return false;
    } else {
        if(confirm("确定删除所选分工委员？")){
            $.ajax({
                url: testurl + "users/delete_cw_group",
                type: "post",
                headers: { "Authorization": "Bearer " + token },
                contentType: "application/json",
                data: JSON.stringify({
                    "group_id": group_id,
                    "ids": ids
                }),
                success: function (data) {
                    if (data.success === true) {
                        $('#my-popup').modal('close');
                        $(".users").html("删除分工委员");
                        $(".alert").html(data.message);
                        $('#my-alert').modal({ target: '#my-alert' });
                    } else {
                        $('#my-popup').modal('close');
                        $(".users").html("删除分工委员");
                        $(".alert").html(data.message);
                        $('#my-alert').modal({ target: '#my-alert' });
                    }
                }
            })
        }
 
    }
});